package cn.itcast.filter16.filter;


import cn.itcast.filter16.entity.User;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;


public class AutoLoginFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {}

    public void doFilter(ServletRequest req, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        // 获取名为autologin的cookie
        Cookie[] cookies = request.getCookies();
        String autologin = null;
        for (Cookie cookie : cookies) {
            if("autologin".equals(cookie.getName())){
                autologin = cookie.getValue();
                break;
            }
        }

        if (autologin != null) {
            // 分割用户名和密码
            String[] parts = autologin.split("-");
            String username = parts[0];
            String password = parts[1];
            // 检查用户名和密码
            if ("chenyu".equals(username) && "202212390606".equals(password)) {
                // 登录成功，将user对象放入session域
                User user = new User();
                user.setUsername(username);
                user.setPassword(password);
                request.getSession().setAttribute("user", user);
            }
        }
        // 放行
        chain.doFilter(request, response);
    }

    public void destroy() {}
}